package gitobject;

import Utils.addUtils;
import Utils.tempWorkTree;
import fileoperation.FileReader;
import sha1.SHA1;
import zlib.ZLibUtils;

import java.io.*;

public class Blob extends GitObject implements Serializable {
    private byte[] value;

    public String getFmt() {
        return fmt;
    }

    public String getMode() {
        return mode;
    }

    public String getPath() {
        return path;
    }

    public String getKey() {
        return key;
    }

    public Blob() {
    }


    /**
     * Constructing blob object from a file
     *
     * @param file
     * @throws Exception
     */
    public Blob(File file) throws Exception {
        fmt = "blob";
        mode = "100644";
        value = getVal(file);
        key = genKey(file);
        compressWrite();
    }

    public static byte[] getVal(File file){
        byte[] bytes= FileReader.readFileByBytes(file);
        return bytes;
    }
    public byte[] getVal(){
        return value;
    }

    /**
     * Deserialize a blob object from an existed hash file in .jit/objects.
     *
     * @param Id
     * @throws IOException
     */
    public static Blob deserialize(String Id) throws IOException {
        try {
            //1.在路径中寻找该文件2.找到之后读取该文件3.将其返回,没找到的话返回null
            File dir = new File(tempWorkTree.gitDir+File.separator+"objects");
            File[] fs = dir.listFiles();//Objects下的文件列表
            for (int i = 0; i < fs.length; i++) {
                if (fs[i].isFile() && fs[i].getName().equals(Id)) {
                    ObjectInputStream objectInputStream = new ObjectInputStream(new FileInputStream(fs[i]));
                    Blob blob = (Blob) objectInputStream.readObject();
                    return blob;
                }
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return null;
    }

    /**
     * Generate key from file.
     *
     * @param file
     * @return String
     * @throws Exception
     */
    public String genKey(File file) throws Exception {//blob文件的key（文件名）为原文件的hash值，直接调用即可
        String blobKey = SHA1.getHash(file);
        return blobKey;
    }

    @Override
    public String toString() {
        return "100644 blob " + key;
    }
}
